"use client";

import { useState } from 'react';
import { 
  Box, Card, CardContent, Grid, Button, Typography, 
  Paper, useTheme, Snackbar, Alert 
} from '@mui/material';

// 计算器主组件
export default function Calculator() {
  const theme = useTheme();
  
  // 状态管理
  const [currentValue, setCurrentValue] = useState('0');
  const [expression, setExpression] = useState('');
  const [waitingForOperand, setWaitingForOperand] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  // 处理数字输入
  const handleDigit = (digit: string) => {
    if (waitingForOperand) {
      setCurrentValue(digit);
      setWaitingForOperand(false);
    } else {
      setCurrentValue(currentValue === '0' ? digit : currentValue + digit);
    }
    setError(null);
  };

  // 处理小数点
  const handleDot = () => {
    if (waitingForOperand) {
      setCurrentValue('0.');
      setWaitingForOperand(false);
    } else if (!currentValue.includes('.')) {
      setCurrentValue(currentValue + '.');
    }
  };

  // 处理运算符
  const handleOperator = (operator: string) => {
    const inputValue = parseFloat(currentValue);
    
    if (expression === '') {
      setExpression(`${currentValue} ${operator}`);
    } else {
      // 当已有表达式时，先计算结果再继续
      calculateResult().then(result => {
        if (result !== null) {
          setExpression(`${result} ${operator}`);
          setCurrentValue(result.toString());
        }
      });
    }
    
    setWaitingForOperand(true);
    setError(null);
  };

  // 调用后端API计算结果
  const calculateResult = async () => {
    if (!expression) return null;
    
    setLoading(true);
    setError(null);
    
    try {
      // 解析表达式获取操作数和运算符
      const parts = expression.split(' ');
      const num1 = parseFloat(parts[0]);
      const operator = parts[1];
      const num2 = parseFloat(currentValue);
      let endpoint;

      switch (operator) {
        case '+':
          endpoint = '/api/Add';
          break;
        case '-':
          endpoint = '/api/Subtract';
          break;
        case '*':
          endpoint = '/api/Multiply';
          break;
        case '/':
          endpoint = '/api/Divide';
          break;
        default:
          throw new Error('无效运算符');
      }

      
      // 调用后端API
      const response = await fetch(endpoint, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ a:num1, b:num2 }),
      });
      
      const data = await response.json();
      
      if (!response.ok) {
        throw new Error(data.error || '计算失败');
      }
      
      // 格式化结果
      const result = Number.isInteger(data.result) 
        ? data.result.toString() 
        : data.result.toFixed(6).replace(/\.?0+$/, '');
      
      setExpression('');
      setCurrentValue(result);
      setWaitingForOperand(true);
      
      return result;
    } catch (err) {
      setError(err instanceof Error ? err.message : '发生未知错误');
      return null;
    } finally {
      setLoading(false);
    }
  };

  // 清除所有
  const handleClear = () => {
    setCurrentValue('0');
    setExpression('');
    setWaitingForOperand(true);
    setError(null);
  };

  // 删除最后一位
  const handleDelete = () => {
    if (currentValue.length > 1) {
      setCurrentValue(currentValue.slice(0, -1));
    } else {
      setCurrentValue('0');
      setWaitingForOperand(true);
    }
  };

  // 渲染按钮
  const renderButton = (
    label: string, 
    variant: 'number' | 'operator' | 'function' | 'equals', 
    onClick: () => void
  ) => {
    const buttonStyles = {
      height: '80px',
      fontSize: '1.5rem',
      fontWeight: 500,
      borderRadius: 2,
      transition: theme.transitions.create(['background-color', 'transform'], {
        duration: 200,
      }),
      '&:active': {
        transform: 'scale(0.98)',
      },
    };
    
    let bgColor, color;
    
    switch (variant) {
        case 'number':
            bgColor = theme.palette.grey[100]; // 正确：使用等号
            color = theme.palette.text.primary; // 正确：使用等号
            break;
        case 'operator':
            bgColor = theme.palette.primary.main; // 正确：使用等号
            color = '#fff'; // 正确：使用等号
            break;
        case 'function':
            bgColor = theme.palette.error.main; // 正确：使用等号
            color = '#fff'; // 正确：使用等号
            break;
        case 'equals':
            bgColor = theme.palette.success.main; // 正确：使用等号
            color = '#fff'; // 正确：使用等号
            break;
        default:
            bgColor = theme.palette.grey[100]; // 正确：使用等号
            color = theme.palette.text.primary; // 正确：使用等号
            break;
    }
    
    return (
      <Button
        variant="contained"
        color={variant === 'number' ? 'inherit' : 
               variant === 'operator' ? 'primary' : 
               variant === 'function' ? 'error' : 'success'}
        onClick={onClick}
        disabled={loading}
        sx={buttonStyles}
        fullWidth
      >
        {label}
      </Button>
    );
  };

  return (
    <Box 
      sx={{ 
        display: 'flex', 
        justifyContent: 'center', 
        alignItems: 'center', 
        minHeight: '100vh',
        backgroundColor: theme.palette.grey[200],
        p: 2
      }}
    >
      <Card 
        sx={{ 
          width: '100%', 
          maxWidth: 400,
          boxShadow: 10,
          borderRadius: 4,
          overflow: 'hidden'
        }}
      >
        <CardContent sx={{ p: 0 }}>
          {/* 显示区域 */}
          <Paper 
            sx={{ 
              backgroundColor: theme.palette.grey[900], 
              color: '#fff',
              p: 3,
              minHeight: 140,
              display: 'flex',
              flexDirection: 'column',
              justifyContent: 'flex-end',
              alignItems: 'flex-end'
            }}
          >
            <Typography 
              variant="body1" 
              sx={{ 
                fontSize: '1rem', 
                color: theme.palette.grey[400],
                mb: 1,
                minHeight: '1.2rem'
              }}
            >
              {expression || ''}
            </Typography>
            <Typography 
              variant="h3" 
              sx={{ 
                fontSize: '2.5rem', 
                fontWeight: 300,
                wordBreak: 'break-all',
                maxWidth: '100%',
                textAlign: 'right'
              }}
            >
              {loading ? '计算中...' : currentValue}
            </Typography>
          </Paper>
          
          {/* 按钮区域 */}
          <Box sx={{ p: 2 }}>
            <Grid container spacing={1}>
              {/* 第一行 */}
              <Grid item xs={3}>
                {renderButton('C', 'function', handleClear)}
              </Grid>
              <Grid item xs={3}>
                {renderButton('⌫', 'function', handleDelete)}
              </Grid>
              <Grid item xs={3}>
                {renderButton('%', 'operator', () => handleOperator('%'))}
              </Grid>
              <Grid item xs={3}>
                {renderButton('÷', 'operator', () => handleOperator('/'))}
              </Grid>
              
              {/* 第二行 */}
              <Grid item xs={3}>
                {renderButton('7', 'number', () => handleDigit('7'))}
              </Grid>
              <Grid item xs={3}>
                {renderButton('8', 'number', () => handleDigit('8'))}
              </Grid>
              <Grid item xs={3}>
                {renderButton('9', 'number', () => handleDigit('9'))}
              </Grid>
              <Grid item xs={3}>
                {renderButton('×', 'operator', () => handleOperator('*'))}
              </Grid>
              
              {/* 第三行 */}
              <Grid item xs={3}>
                {renderButton('4', 'number', () => handleDigit('4'))}
              </Grid>
              <Grid item xs={3}>
                {renderButton('5', 'number', () => handleDigit('5'))}
              </Grid>
              <Grid item xs={3}>
                {renderButton('6', 'number', () => handleDigit('6'))}
              </Grid>
              <Grid item xs={3}>
                {renderButton('-', 'operator', () => handleOperator('-'))}
              </Grid>
              
              {/* 第四行 */}
              <Grid item xs={3}>
                {renderButton('1', 'number', () => handleDigit('1'))}
              </Grid>
              <Grid item xs={3}>
                {renderButton('2', 'number', () => handleDigit('2'))}
              </Grid>
              <Grid item xs={3}>
                {renderButton('3', 'number', () => handleDigit('3'))}
              </Grid>
              <Grid item xs={3}>
                {renderButton('+', 'operator', () => handleOperator('+'))}
              </Grid>
              
              {/* 第五行 */}
              <Grid item xs={6}>
                {renderButton('0', 'number', () => handleDigit('0'))}
              </Grid>
              <Grid item xs={3}>
                {renderButton('.', 'number', handleDot)}
              </Grid>
              <Grid item xs={3}>
                {renderButton('=', 'equals', calculateResult)}
              </Grid>
            </Grid>
          </Box>
        </CardContent>
      </Card>
      
      {/* 错误提示 */}
      <Snackbar 
        open={!!error} 
        autoHideDuration={6000} 
        onClose={() => setError(null)}
        anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
      >
        <Alert onClose={() => setError(null)} severity="error" sx={{ width: '100%' }}>
          {error}
        </Alert>
      </Snackbar>
    </Box>
  );
}